package com.speechb.interceptor;

import com.speechb.common.logger.AppLoggerFactory;
import com.speechb.common.text.IpUtil;
import org.slf4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Map;

/**
 * 请求参数日志拦截器
 */
public class RequestInfoInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = AppLoggerFactory.getRunLogger();

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        if (!logger.isDebugEnabled()) {
            return super.preHandle(request, response, handler);
        }
        // 所有请求第一个进入的方法
        String reqURL = request.getRequestURL().toString();
        String ip = request.getRemoteHost();
        // InputStream is = request.getInputStream();

        /*StringBuilder responseStrBuilder = new StringBuilder();*/
/*		BufferedReader streamReader = new BufferedReader(new InputStreamReader(
				is, "UTF-8"));*///加上这段获取不到数据
/*		while ((inputStr = streamReader.readLine()) != null)
			responseStrBuilder.append(inputStr);*/
        // System.out.println("请求参数: " + responseStrBuilder.toString ());
        //String parmeter = responseStrBuilder.toString();

        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        StringBuilder sb = new StringBuilder();
        sb.append("\n-------------------------------请求信息-----------------------------\n");
        if (handler instanceof HandlerMethod) {
            String sessionId = request.getSession().getId();
            HandlerMethod h = (HandlerMethod) handler;
            // Controller 的包名
            sb.append("Controller:  ").append(h.getBean().getClass().getName())
                    .append("\n");
            // 方法名称
            sb.append("Method:  ").append(h.getMethod().getName())
                    .append("\n");
            // 请求方式 post\put\get 等等
            sb.append("RequestMethod:  ").append(request.getMethod())
                    .append("\n");
            // 所有的请求参数
            sb.append("Params:  ");
            Map<String, String[]> map = request.getParameterMap();
            Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String key = parameterNames.nextElement();
                sb.append(key).append("=");
                for (String value : map.get(key)) {
                    sb.append(value).append("  ");
                }
                sb.append(";");
            }
            sb.append("\n");
            // 部分请求链接
            sb.append("URI:  ").append(request.getRequestURI())
                    .append("\n");
            // 完整的请求链接
            sb.append("AllURI: ").append(reqURL).append("\n");
            // 请求方的 ip地址
            sb.append("request IP: ").append(IpUtil.getIpAddr(request)).append("\n");
            sb.append("Session Id:  ").append(sessionId).append("\n");
            sb.append("------------------------------------------------------------\n");
            logger.debug(sb.toString());
        }
        return super.preHandle(request, response, handler);
    }
}
